'use client';

import React, { Fragment, useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Listbox, Transition } from '@headlessui/react';
import { ChevronUpDownIcon, CheckIcon, PlusIcon } from '@heroicons/react/24/outline';
import { cn } from '@/utils';

export interface SelectOption {
  id: string;
  label: string;
  value: any;
  icon?: React.ReactNode;
  color?: string;
  disabled?: boolean;
}

export interface SelectProps {
  options: SelectOption[];
  value?: SelectOption | SelectOption[];
  onChange: (value: SelectOption | SelectOption[]) => void;
  placeholder?: string;
  multiple?: boolean;
  disabled?: boolean;
  error?: string;
  success?: string;
  label?: string;
  searchable?: boolean;
  creatable?: boolean;
  onCreateOption?: (inputValue: string) => void;
  className?: string;
  size?: 'sm' | 'md' | 'lg';
  variant?: 'default' | 'filled';
}

const Select: React.FC<SelectProps> = ({
  options,
  value,
  onChange,
  placeholder = '请选择...',
  multiple = false,
  disabled = false,
  error,
  success,
  label,
  searchable = false,
  creatable = false,
  onCreateOption,
  className,
  size = 'md',
  variant = 'default',
}) => {
  const [query, setQuery] = useState('');
  
  // 过滤选项
  const filteredOptions = searchable
    ? options.filter((option) => 
        option.label.toLowerCase().includes(query.toLowerCase())
      )
    : options;

  // 显示创建选项
  const showCreateOption = creatable && query && !filteredOptions.some(
    (option) => option.label.toLowerCase() === query.toLowerCase()
  );

  // 获取显示的值
  const getDisplayValue = () => {
    if (multiple && Array.isArray(value)) {
      if (value.length === 0) return placeholder;
      if (value.length === 1) return value[0].label;
      return `已选择 ${value.length} 项`;
    }
    
    if (!multiple && value && !Array.isArray(value)) {
      return value.label;
    }
    
    return placeholder;
  };

  // 处理选项选择
  const handleSelect = (selectedOption: SelectOption) => {
    if (multiple) {
      const currentValues = Array.isArray(value) ? value : [];
      const isSelected = currentValues.some(v => v.id === selectedOption.id);
      
      if (isSelected) {
        onChange(currentValues.filter(v => v.id !== selectedOption.id));
      } else {
        onChange([...currentValues, selectedOption]);
      }
    } else {
      onChange(selectedOption);
    }
  };

  // 处理创建新选项
  const handleCreate = () => {
    if (onCreateOption && query.trim()) {
      onCreateOption(query.trim());
      setQuery('');
    }
  };

  // 检查选项是否被选中
  const isSelected = (option: SelectOption) => {
    if (multiple && Array.isArray(value)) {
      return value.some(v => v.id === option.id);
    }
    return !multiple && value && !Array.isArray(value) && value.id === option.id;
  };

  const sizeClasses = {
    sm: 'px-3 py-2 text-sm',
    md: 'px-4 py-3 text-base',
    lg: 'px-5 py-4 text-lg',
  };

  const buttonClasses = cn(
    // 基础样式
    'relative w-full cursor-pointer rounded-xl border transition-all duration-200',
    'text-left focus:outline-none focus-visible:ring-4',
    
    // 尺寸
    sizeClasses[size],
    
    // 变体样式
    {
      // Default
      'bg-white border-gray-200 hover:border-gray-300 focus-visible:border-blue-500 focus-visible:ring-blue-500/10':
        variant === 'default' && !error && !success,
      
      // Filled
      'bg-gray-50 border-transparent hover:bg-gray-100 focus-visible:bg-white focus-visible:border-blue-500 focus-visible:ring-blue-500/10':
        variant === 'filled' && !error && !success,
    },
    
    // 状态样式
    {
      'border-red-300 focus-visible:border-red-500 focus-visible:ring-red-500/10': error,
      'border-green-300 focus-visible:border-green-500 focus-visible:ring-green-500/10': success,
      'opacity-50 cursor-not-allowed': disabled,
    },
    
    className
  );

  return (
    <div className="space-y-1">
      {label && (
        <label className={cn(
          'block text-sm font-medium transition-colors duration-200',
          {
            'text-gray-700': !error && !success,
            'text-red-600': error,
            'text-green-600': success,
          }
        )}>
          {label}
        </label>
      )}
      
      <Listbox value={value} onChange={onChange} disabled={disabled} multiple={multiple}>
        <div className="relative">
          <Listbox.Button className={buttonClasses}>
            <span className="flex items-center justify-between">
              <span className={cn(
                'block truncate',
                {
                  'text-gray-400': !value || (Array.isArray(value) && value.length === 0),
                  'text-gray-900': value && (!Array.isArray(value) || value.length > 0),
                }
              )}>
                {getDisplayValue()}
              </span>
              
              <ChevronUpDownIcon className="h-5 w-5 text-gray-400 flex-shrink-0" />
            </span>
          </Listbox.Button>
          
          <Transition
            as={Fragment}
            leave="transition ease-in duration-100"
            leaveFrom="opacity-100"
            leaveTo="opacity-0"
          >
            <Listbox.Options className="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-xl bg-white py-1 shadow-lg ring-1 ring-black/5 focus:outline-none">
              {/* 搜索框 */}
              {searchable && (
                <div className="sticky top-0 bg-white px-2 py-2 border-b border-gray-100">
                  <input
                    type="text"
                    placeholder="搜索选项..."
                    value={query}
                    onChange={(e) => setQuery(e.target.value)}
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:border-blue-500"
                  />
                </div>
              )}
              
              {/* 创建新选项 */}
              {showCreateOption && (
                <motion.div
                  initial={{ opacity: 0, y: -10 }}
                  animate={{ opacity: 1, y: 0 }}
                  className="px-2 py-1"
                >
                  <button
                    onClick={handleCreate}
                    className="w-full flex items-center gap-2 px-3 py-2 text-sm text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                  >
                    <PlusIcon className="w-4 h-4" />
                    创建 "{query}"
                  </button>
                </motion.div>
              )}
              
              {/* 选项列表 */}
              <AnimatePresence>
                {filteredOptions.length === 0 && !showCreateOption ? (
                  <div className="px-4 py-3 text-sm text-gray-500 text-center">
                    {searchable ? '没有找到匹配的选项' : '暂无选项'}
                  </div>
                ) : (
                  filteredOptions.map((option, index) => (
                    <Listbox.Option
                      key={option.id}
                      value={option}
                      disabled={option.disabled}
                      className={({ active, selected }) =>
                        cn(
                          'relative cursor-pointer select-none py-2 pl-3 pr-9 mx-1 rounded-lg transition-colors',
                          {
                            'bg-blue-50 text-blue-900': active,
                            'text-gray-900': !active,
                            'opacity-50 cursor-not-allowed': option.disabled,
                          }
                        )
                      }
                    >
                      {({ selected }) => (
                        <motion.div
                          initial={{ opacity: 0, x: -10 }}
                          animate={{ opacity: 1, x: 0 }}
                          transition={{ delay: index * 0.02 }}
                          className="flex items-center gap-2"
                        >
                          {/* 选项图标/颜色 */}
                          {option.icon && (
                            <span className="flex-shrink-0 w-5 h-5">
                              {option.icon}
                            </span>
                          )}
                          
                          {option.color && (
                            <span
                              className="flex-shrink-0 w-3 h-3 rounded-full"
                              style={{ backgroundColor: option.color }}
                            />
                          )}
                          
                          {/* 选项文本 */}
                          <span className={cn(
                            'block truncate',
                            {
                              'font-medium': isSelected(option),
                              'font-normal': !isSelected(option),
                            }
                          )}>
                            {option.label}
                          </span>
                          
                          {/* 选中状态 */}
                          {isSelected(option) && (
                            <span className="absolute inset-y-0 right-0 flex items-center pr-3 text-blue-600">
                              <CheckIcon className="h-4 w-4" />
                            </span>
                          )}
                        </motion.div>
                      )}
                    </Listbox.Option>
                  ))
                )}
              </AnimatePresence>
            </Listbox.Options>
          </Transition>
        </div>
      </Listbox>
      
      {/* 多选显示 */}
      {multiple && Array.isArray(value) && value.length > 0 && (
        <motion.div
          initial={{ opacity: 0, height: 0 }}
          animate={{ opacity: 1, height: 'auto' }}
          className="flex flex-wrap gap-1 mt-2"
        >
          {value.map((selectedOption) => (
            <motion.span
              key={selectedOption.id}
              initial={{ opacity: 0, scale: 0.8 }}
              animate={{ opacity: 1, scale: 1 }}
              className="inline-flex items-center gap-1 px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-md"
            >
              {selectedOption.icon && (
                <span className="w-3 h-3">{selectedOption.icon}</span>
              )}
              {selectedOption.color && (
                <span
                  className="w-2 h-2 rounded-full"
                  style={{ backgroundColor: selectedOption.color }}
                />
              )}
              {selectedOption.label}
              <button
                onClick={() => handleSelect(selectedOption)}
                className="ml-1 hover:text-blue-900"
              >
                ×
              </button>
            </motion.span>
          ))}
        </motion.div>
      )}
      
      {/* 错误或成功消息 */}
      <AnimatePresence mode="wait">
        {(error || success) && (
          <motion.div
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            transition={{ duration: 0.2 }}
            className={cn(
              'text-xs font-medium',
              {
                'text-red-600': error,
                'text-green-600': success,
              }
            )}
          >
            {error || success}
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
};

export default Select;